var express = require("express");
var router = express.Router();
var {showType} = require("./tree");
var { userModel,shopTypeModel ,couponModel,UserCoupon} = require("../../model/model");


router.get('/shopType',async (req,res)=>{
    let data = await shopTypeModel.find().lean();
    let list = showType(data);
    console.log(list)
    res.send({
        code:200,
        list
    })
}
)


router.get('/coupon',async(req,res)=>{
    let {couponId,num} = req.query;
   
    if(couponId){
       if(num!==0){
        num=0
       }else{
        num=1
       }
         await couponModel.updateOne(
          { _id: couponId },
          { num: num+1 }
         )
        let ls = await couponModel.find().populate("cid");


           
       
      
       
        res.send({
          code: 200,
          list: ls,
          list1:ls[0].list,
     
     
        });
       

    }else{
         let ls = await couponModel.find();
         res.send({
           code: 200,
           list: ls,
    
         });
    }
   
})

router.post("/claim-coupon", async (req, res) => {
  const { userId, couponId } = req.body; 

    // 记录用户领取优惠券
  let data =  await UserCoupon.create({ userId, couponId });



  // console.log(data)

    res.send({
      code: 200,
      message: "领取成功",
      CouponStatus:data.status,
      CouponId:data.couponId
    })
});

router.post('/addCoupon',(req,res)=>{

  couponModel.create(req.body)
  res.send({
    code:200,
    message:'添加成功'
  })
})

module.exports = router;